import sys
sys.path.append("..")   #也可以这样
import cv2
from config import kLocUserImagesPath
from uuid import uuid4
from celerytask import app
from utils.image_utils import add_watermark_to_image
from config import kFontPath
# 上传到阿里云的代码
from utils.cloud_utils import upload_file_to_aliyun, transform_path, upload_file_to_qiniu
import os


def transform_data(input_data):
    output_data = {
        "shuiyin": input_data["shuiyin"],
        "oss_name": input_data["oss_name"]
    }
    # 转换图片URL
    output_data["target_image"] = input_data.get("source_image")
    output_data["source_images"] = []
    
    # 遍历faces_data
    for face_data in input_data.get("faces_data", []):
        transformed_face_data = {
            "index": face_data["index"],
            "face_image_urls": [face_data["face_image_url"]]
        }
        output_data["source_images"].append(transformed_face_data)
    
    
    return output_data

def swap_faces_one_image(data,status="success"):
    import time
    start = time.time()
    request_data = transform_data(data)
    process_workflow = app.tasks['celerytask.tasks.start_V2']  # 图片换脸的流程api
    print (request_data)
    output_path = process_workflow.apply_async(args=[request_data,
                                                     f'{kLocUserImagesPath}/filename_Many_{uuid4().hex}.jpg']
                                              ).get(timeout=15)   # 加入了一个time_out
    if request_data["shuiyin"]:
        add_watermark_to_image(output_path, "Generated by AI", kFontPath)

    aliyun_file_path = transform_path(output_path, folder_name="swap_face")
    if request_data["oss_name"] == "qiniu":
        cloud_file_url = upload_file_to_qiniu(
            aliyun_file_path, output_path
        )
    else:
        cloud_file_url = upload_file_to_aliyun(
            aliyun_file_path, output_path
        )
    # 删除本地的文件
    os.remove(output_path)
    
    if "aliyuncs.com" in cloud_file_url:
        ali_file_name = cloud_file_url.split("aliyuncs.com/")[-1]
    else:
        ali_file_name = cloud_file_url

    return {
        "status": status,
        "result": {
            "ali_all_url": cloud_file_url,
            # 如果有 url 的值,就用 split("aliyuncs.com/")[-1] 来获取到文件名,否则就是空字符串
            "ali_file_name": ali_file_name,
        },
        "cost_time": time.time() - start
        # "errors": self.errors,
        # "warnings": self.warnings
    }


if __name__ == "__main__":

    data = {
      "source_image": "https://ty-huanlian.oss-cn-shanghai.aliyuncs.com/test/WX20230831-151640%402x.png",
      "faces_data": [
        {
          "index": 0,
          "face_image_url": "http://usfile.chaotuapp.com/uploads/android/user/1693484879724.jpg"
        },
        {
          "index": 0,
          "face_image_url": "img/1698212401438.jpg"
        }
      ],
        "shuiyin": 1,
        "oss_name": "ali"
    }



    print (swap_faces_one_image(data))